package com.exp.bookhouse.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;      //缩略图使用

    @Value("${images.path}")
    private String upUrl;


    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址,不带分组的路径  M00/00/00/rBLnQ17TRjmASpWWAAA0UWdASJs550.png
     * @throws IOException s
     */
    public String uploadFile(MultipartFile file) throws IOException {
//        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
//                FilenameUtils.getExtension(file.getOriginalFilename()), null);
//        return storePath.getPath();
        String fileName = file.getOriginalFilename();//获取文件名
        fileName = getFileName(fileName);
        String filePath = upUrl;
        if(!file.isEmpty()){
            try(BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(filePath+File.separator+fileName)))){
                out.write(file.getBytes());
                out.flush();
                return fileName;
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
            return fileName;
    }
    //在文件名后缀前加一个时间戳
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 文件下载
     * @param groupName 组名           如：group1
     * @param path 不带组名的文件路径  如：M00/00/00/rBLnQ165PGKAICk_AAA0UWdASJs298_60x60.png
     * @param downUrl 下载到哪的目录   如：C:\\Users\\Linging\\Desktop"
     */
    public void downFile(String groupName, String path, String downUrl){
        try {
            File file = new File(path);
            String path1 = file.getPath();
            String suffix = path1.substring(path1.lastIndexOf("."));
            byte[] bytes = storageClient.downloadFile(groupName, path, new DownloadByteArray());
            String url = downUrl+"\\"+ System.currentTimeMillis()+suffix;   //下载的路径
            FileOutputStream stream = new FileOutputStream(url);
            stream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//    /**
//     * 删除文件
//     * @param groupName 组名  如：group1
//     * @param path 路径    如：M00/00/00/rBLnQ165QzaAURSEAAA0UWdASJs476.jpg
//     */
//    public void deleteFile(String groupName, String path) {
//        storageClient.deleteFile(groupName,path);
//    }

    /**
     * 删除本地图片服务器文件
     * @param filename 文件名称
     */
    public void deleteFile(String filename){
//        storageClient.deleteFile(path);
        String imagePath = upUrl+"\\"+filename;//图片路径
        File file = new File(imagePath);
        if(file.exists()){//文件存在删除文件
            file.delete();
        }
    }
}